package dao;

import BaseQuery.BaseQuery;
import Bean.Employee;
import Utils.JdbcUtils;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class EmployeeDao implements BaseDao<Employee>,PageDao<Employee> {
	@Override
	public int add(Employee employee) throws SQLException {
		Connection connection= JdbcUtils.getConn();
		String sql="INSERT INTO emp(ename,job,hiredate,sal,deptno) VALUES (?,?,?,?,?);";
		return JdbcUtils.getQueryRunner().update(sql,employee.getEname(),employee.getJob(),
				employee.getHiredate(),employee.getSal(),employee.getDeptno());
	}
	@Override
	public int update(Employee employee) throws SQLException {
		String sql = "update emp set ename=?,job=?,hiredate=?,sal=?,deptno=? where empno=?";
		return JdbcUtils.getQueryRunner().update(sql,
				employee.getEname(),employee.getJob(),
				employee.getHiredate(),employee.getSal(),
				employee.getDeptno(),employee.getEmpno());
	}


	@Override
	public int delete(Integer id) throws SQLException {
		String sql = "delete from emp where empno=?";
		return JdbcUtils.getQueryRunner().update(sql,id);
	}

	@Override
	public Employee getById(Integer id) throws SQLException {
		Connection connection=JdbcUtils.getConn();
		String sql="select empno,ename,job,hiredate,sal,deptno from emp where empno=?";
		return JdbcUtils.getQueryRunner().query(sql,new BeanHandler<Employee>(Employee.class),id);
	}

	@Override
	public List<Employee> getAll() throws SQLException {
		String sql="select empno,ename,job,hiredate,sal,deptno from emp";
		return JdbcUtils.getQueryRunner().query(sql,new BeanListHandler<Employee>(Employee.class));
	}

	@Override
	public int getCount() throws SQLException {
		String sql="select count(empno) from emp";
		long count=JdbcUtils.getQueryRunner().query(sql,new ScalarHandler<Long>());
		return  (int ) count;
	}

	@Override
	public List<Employee> getByPage(BaseQuery baseQuery) throws SQLException {
		String sql="select *from emp limit ?,?;";
		return JdbcUtils.getQueryRunner().query(sql,new BeanListHandler<Employee>(Employee.class),baseQuery.startIndex(),baseQuery.getPageCount());
	}
}
